<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑日志 - 内容评级平台</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.css" rel="stylesheet">
    <style>
        /* CSS 样式保持不变 */
        :root {
            --primary: #4361ee;
            --secondary: #3f37c9;
            --accent: #4cc9f0;
            --dark: #1d3557;
            --darker: #0d1b2a;
            --light: #f8f9fa;
            --gray: #8d99ae;
            --success: #4caf50;
            --warning: #ff9800;
            --danger: #f44336;
            --card-bg: rgba(29, 53, 87, 0.8);
            --transition: all 0.3s ease;
        }
        body {
            background: linear-gradient(135deg, var(--darker) 0%, var(--dark) 100%);
            color: var(--light);
            min-height: 100vh;
            background-attachment: fixed;
            line-height: 1.6;
        }
        .main-content {
            max-width: 1400px;
            margin: 2rem auto;
            padding: 0 2rem;
        }
        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
        }
        .section-title {
            font-size: 1.8rem;
            font-weight: 700;
            position: relative;
            padding-left: 1rem;
        }
        .section-title::before {
            content: "";
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            width: 4px;
            background: var(--accent);
            border-radius: 2px;
        }
        .blog-card {
            background: var(--card-bg);
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            transition: var(--transition);
        }
        .blog-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
        }
        .form-group {
            margin-bottom: 1.5rem;
        }
        label {
            display: block;
            margin-bottom: 0.5rem;
            color: var(--accent);
        }
        input[type="text"], textarea {
            width: 100%;
            padding: 0.75rem;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            color: var(--light);
            transition: var(--transition);
        }
        input[type="text"]:focus, textarea:focus {
            outline: none;
            border-color: var(--accent);
            box-shadow: 0 0 0 3px rgba(76, 201, 240, 0.2);
        }
        .action-btn {
            display: flex;
            align-items: center;
            gap: 5px;
            color: var(--light);
            background: rgba(255, 255, 255, 0.1);
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 30px;
            cursor: pointer;
            transition: var(--transition);
            text-decoration: none;
            font-size: 0.9rem;
        }
        .action-btn:hover {
            background: rgba(255, 255, 255, 0.2);
        }
        .btn-primary {
            background: var(--primary);
            color: white;
            font-weight: 600;
        }
        .btn-primary:hover {
            background: var(--secondary);
            color: white;
        }
        .summernote {
            background-color: white;
            color: #333;
            border-radius: 8px;
        }
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: var(--gray);
        }
        .empty-state i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: var(--accent);
        }
    </style>
</head>
<body>
<jsp:include page="header.jsp" />
<div class="main-content">
    <div class="section-header">
        <h2 class="section-title">
            <%= request.getParameter("blogId") != null ? "编辑日志" : "写新日志" %>
        </h2>
        <a href="blog-list.jsp" class="action-btn"><i class="fas fa-list"></i> 日志列表</a>
    </div>
    <div class="blog-card">
        <form id="blogForm">
            <!-- 隐藏字段用于区分操作类型和传递blogId -->
            <input type="hidden" name="action" id="action" value="<%= request.getParameter("blogId") != null ? "update" : "add" %>">
            <input type="hidden" name="blogId" id="blogId" value="<%= request.getParameter("blogId") != null ? request.getParameter("blogId") : "" %>">
            <div class="form-group">
                <label for="title">日志标题</label>
                <input type="text" id="title" name="title" placeholder="请输入日志标题" required>
            </div>
            <div class="form-group">
                <label for="content">日志内容</label>
                <textarea id="content" name="content" rows="10" placeholder="请输入日志内容"></textarea>
            </div>
            <div class="form-group text-end">
                <button type="submit" class="action-btn btn-primary"><i class="fas fa-save"></i> 保存日志</button>
                <a href="blog-list.jsp" class="action-btn"><i class="fas fa-times"></i> 取消</a>
            </div>
        </form>
    </div>
</div>
<jsp:include page="footer.jsp" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.js"></script>
<script>
    $(document).ready(function() {
        // 初始化Summernote富文本编辑器
        $('#content').summernote({
            height: 300,
            placeholder: '请输入日志内容，支持富文本格式...',
            toolbar: [
                ['style', ['bold', 'italic', 'underline', 'clear']],
                ['font', ['strikethrough', 'superscript', 'subscript']],
                ['fontsize', ['fontsize']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link', 'picture', 'video']],
                ['view', ['fullscreen', 'codeview', 'help']]
            ]
        });

        // 如果是编辑模式，加载日志数据
        const blogId = $('#blogId').val();
        console.log('当前编辑的blogId:', blogId);
        if (blogId) {
            console.log('当前编辑的blogId:', blogId);
            $.ajax({
                url: '${pageContext.request.contextPath}/blog?blogId=' + encodeURIComponent(blogId),
                type: 'GET',
                success: function(response) {
                    try {
                        // 尝试解析响应
                        const data = typeof response === 'object' ? response : JSON.parse(response);

                        if (data.success && data.blog) {
                            // 填充表单
                            $('#title').val(data.blog.title);
                            $('#content').summernote('code', data.blog.content);
                        } else {
                            alert('加载日志数据失败：' + (data.message || '未找到匹配的日志'));
                            window.location.href = 'blog-list.jsp';
                        }
                    } catch (e) {
                        console.error('解析响应失败:', e, '原始响应:', response);
                        alert('加载失败：服务器返回了无效响应');
                        window.location.href = 'blog-list.jsp';
                    }
                },
                error: function(xhr) {
                    console.error('请求失败:', xhr);
                    try {
                        const errorResponse = JSON.parse(xhr.responseText);
                        alert('加载失败: ' + errorResponse.message);
                    } catch (e) {
                        alert(`服务器错误: ${xhr.status} ${xhr.statusText}`);
                    }
                    window.location.href = 'blog-list.jsp';
                }
            });
        }

        // 修复的表单提交处理
        $('#blogForm').submit(function(e) {
            e.preventDefault();

            // 获取表单数据
            const action = $('#action').val();
            const blogId = $('#blogId').val();
            const title = $('#title').val().trim();
            const content = $('#content').summernote('code').trim();

            // 验证标题
            if (!title) {
                alert('标题不能为空');
                return;
            }

            // 验证内容
            if (!content) {
                alert('内容不能为空');
                return;
            }

            console.log('提交表单: action=' + action + ', blogId=' + blogId + ', title=' + title);

            // 构建数据对象
            const data = {
                action: action,
                blogId: blogId,
                title: title,
                content: content
            };

            // 发送AJAX请求
            $.ajax({
                url: '${pageContext.request.contextPath}/blog',
                type: 'POST',
                data: {
                    action: action,
                    blogId: blogId,
                    title: title,
                    content: content
                },
                dataType: 'json',
                success: function(data) {
                    if (data.success) {
                        alert('保存成功');
                        // 改为跳转到博客列表页（根据要求）
                        window.location.href = 'blog-list.jsp';
                    } else {
                        alert('保存失败: ' + data.message);
                    }
                },
                error: function(xhr) {
                    try {
                        // 尝试解析错误响应
                        const errorData = JSON.parse(xhr.responseText);
                        alert('请求失败: ' + (errorData.message || xhr.statusText));
                    } catch (e) {
                        // 响应不是JSON，显示原始文本
                        alert('服务器错误: ' + xhr.statusText);
                    }
                }
            });
        });
    });
</script>
</body>
</html>